<?php
namespace app\admin\model;

use think\Db;

class MsgModel extends BaseModel{
    // 确定链接表名
    protected $name = 'admin_msg';
	/**
	 * [保存推送消息]
	 */
	public function saveMsgPush($uid,$send_id,$savedMsg,$msg) {
		$this::startTrans();
		try {
			$ids_arr = explode(",",$uid);
			foreach($ids_arr as &$v){
				$v = "|".$v."|";
			}
			$ids_arr[] = "|".$send_id."|";
			$ids_str = implode(",",$ids_arr);
			$check = $this::where('msg_type',1)->value('msg');
			$data = [
				'user_ids' => $ids_str,
				'update_at' => time(),
				'read_ids' => '',
				'msg' => $savedMsg,
				'msg_type' => 1,
				'msg_name' => "系统推送消息",
				'last_msg' => $msg,
				'last_user_id' => $send_id
			];
			if($check){
				$data['msg'] = $check.$savedMsg;
				$this::where('msg_type',1)->update($data);
			}else{
				$this::insert($data);
			}
			$this::commit();
			return ['code'=>1,'msg'=>'保存成功'];
		} catch (\Exception $e) {
			$this::rollback();
			return ['code'=>0,'msg'=>'保存失败：'.$e->getMessage()];
		}
	}
	/**
	 * [保存会话消息]
	 */
	public function saveConversation($msg_id,$send_id,$savedMsg,$msg) {
		$this::startTrans();
		try {
			$check = $this::where('id',$msg_id)->value('msg');
			$data = [
				'update_at' => time(),
				'read_ids' => '|'.session('id').'|',
				'msg' => $check.$savedMsg,
				'last_msg' => $msg,
				'last_user_id' => $send_id
			];
			$this::where('id',$msg_id)->update($data);
			$this::commit();
			return ['code'=>1,'msg'=>'保存成功'];
		} catch (\Exception $e) {
			$this::rollback();
			return ['code'=>0,'msg'=>'保存失败：'.$e->getMessage()];
		}
	}
}
